package com.foreveross.taskservice.taskcache.redis.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.charset.Charset;

import org.apache.commons.lang3.SerializationUtils;

/**
 * 封装对对象的序列化，大部分用apache来实现
 * 字符串用类似spring的string序列化做法，UTF-8编码
 * @author Administrator
 *
 */
public class RedisSerializeUtil {
	
	public static byte[] serializeObject(Serializable obj){
		return SerializationUtils.serialize(obj);
	}
	
	//序列化
	public static byte[] serialize(Object object) {
		ObjectOutputStream oos = null;
		ByteArrayOutputStream baos = null;
		try {
			// 序列化
			baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			oos.writeObject(object);
			byte[] bytes = baos.toByteArray();
			return bytes;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	//反序列化
	public static Object unserialize(byte[] bytes) {
		ByteArrayInputStream bais = null;
		try {
			// 反序列化
			bais = new ByteArrayInputStream(bytes);
			ObjectInputStream ois = new ObjectInputStream(bais);
			return ois.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static byte[] serializeString(String str){
		return str==null?null:str.getBytes(getCharset());
	}
	public static Object deserializeObject(byte[] b){
		return SerializationUtils.deserialize(b);
	}
	@SuppressWarnings("unchecked")
	public static <T> T deserializeObject(byte[] b,Class<T> clzz){
		return (T)SerializationUtils.deserialize(b);
	}
	public static String deserializeString(byte[] b){
		return b==null?null:new String(b,getCharset());
	}
	private static Charset getCharset(){
		return Charset.forName("UTF8");
	}
	
	
}
